﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Brilliant.ORM
{
    /// <summary>
    /// 实体基类
    /// </summary>
    public class EntityBase
    {
        //外键关联对象
        private EntityBase fkObject;

        //实体属性列表（键值对）
        private IDictionary<string, object> fields = new Dictionary<string, object>();

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public EntityBase() { }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fkObject">外键关联对象</param>
        public EntityBase(EntityBase fkObject)
        {
            this.fkObject = fkObject;
        }

        /// <summary>
        /// 设置属性的值
        /// </summary>
        /// <param name="propertyName">属性名</param>
        /// <param name="value">属性值</param>
        public void SetProperty(string propertyName, object value)
        {
            propertyName = propertyName.ToLower();
            if (fkObject != null) //如果外键关联对象不为空
            {
                this.fields = fkObject.fields;
            }
            if (fields.ContainsKey(propertyName))
            {
                fields[propertyName] = value;
            }
            else
            {
                fields.Add(propertyName, value);
            }
        }

        /// <summary>
        /// 获取属性的值
        /// </summary>
        /// <typeparam name="T">用以指明属性类型</typeparam>
        /// <param name="propertyName">属性名</param>
        /// <returns>属性的值</returns>
        public T GetProperty<T>(string propertyName)
        {
            propertyName = propertyName.ToLower();
            if (fkObject != null) //如果外键关联对象不为空
            {
                this.fields = fkObject.fields;
            }
            if (fields.ContainsKey(propertyName))
            {
                if (DBNull.Value == fields[propertyName])
                {
                    return default(T);
                }
                return (T)fields[propertyName];
            }
            return default(T);
        }

        /// <summary>
        /// 属性索引器
        /// </summary>
        /// <param name="propertyName">属性名称</param>
        /// <returns>属性值</returns>
        public object this[string propertyName]
        {
            get
            {
                string key = propertyName.ToLower();
                if (fields.ContainsKey(key))
                {
                    return fields[key];
                }
                return null;
            }
        }
    }
}
